package com.leonzhangxf.spel.reference;

import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.util.Arrays;
import java.util.Objects;

/**
 * Array Construction
 * <p>
 * You cannot currently supply an initializer when you construct multi-dimensional array.
 *
 * @author leonzhangxf
 * @date 20190427
 */
public class ArrayConstruction {

    public static void main(String[] args) {
        SpelParserConfiguration parserConfiguration =
            new SpelParserConfiguration(true, true);
        SpelExpressionParser parser = new SpelExpressionParser(parserConfiguration);
        SimpleEvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();

        int[] numbers1 = (int[]) parser.parseExpression("new int[4]{0,1,2,3}").getValue(context);
        Arrays.stream(Objects.requireNonNull(numbers1)).forEach(System.out::println);

        // Array with initializer
        System.out.println("============================");
        int[] numbers2 = (int[]) parser.parseExpression("new int[]{1,2,3}").getValue(context);
        Arrays.stream(Objects.requireNonNull(numbers2)).forEach(System.out::println);

        // Multi dimensional array
        System.out.println("============================");
        try {
            // Cannot currently supply an initializer when you construct multi-dimensional array.
            int[][] numbers3 = (int[][]) parser.parseExpression("new int[2][2]{{1,1}, {2,2}}")
                .getValue(context);
            Arrays.stream(Objects.requireNonNull(numbers3)).forEach(System.out::println);
        } catch (SpelEvaluationException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
